package com.chinaisafe.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.chinaisafe.user.entity.SysApp;
import com.chinaisafe.user.mapper.SysAppMapper;
import com.chinaisafe.user.service.SysAppService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaisafe.user.vo.request.SysAppReqVO;
import com.chinaisafe.user.vo.response.SysAppRespVO;
import org.springframework.stereotype.Service;
import com.chinaisafe.base.common.exception.BizException;
import com.chinaisafe.base.mybatisplus.constant.MybatisplusConstants;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaisafe.base.mybatisplus.util.MpQueryWrapperPageUtil;

import java.util.Arrays;
import java.util.Optional;
/**
 * SysAppServiceImpl
 * Description：应用服务实现类
 *
 * @author tby
 * @date 2024-07-11 17:32:41
 */
@Service
public class SysAppServiceImpl extends ServiceImpl<SysAppMapper, SysApp> implements SysAppService {

    @Override
    public IPage<SysAppRespVO> getPageList(SysAppReqVO sysAppReqVO) {
        // 分页设置
        Page<SysApp> page = MpQueryWrapperPageUtil.buildWrapperPage(new Page<>(), sysAppReqVO);
        // 查询条件构造
        QueryWrapper<SysApp> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(SysApp::getDeleted, MybatisplusConstants.LOGIC_NOT_DELETE_VALUE)
                .like(StrUtil.isNotBlank(sysAppReqVO.getName()),SysApp::getName, sysAppReqVO.getName())
                .eq(StrUtil.isNotBlank(sysAppReqVO.getClientType()),SysApp::getClientType, sysAppReqVO.getClientType())
                .orderByAsc(SysApp::getSeq);
        return baseMapper.getPageList(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysAppRespVO add(SysAppReqVO sysAppReqVO) {
        checkRepeat(sysAppReqVO);
        // 新增和编辑逻辑相同的情况下 直接调用新增或编辑方法
        return this.addOrUpdate(sysAppReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysAppRespVO update(SysAppReqVO sysAppReqVO) {
        SysApp sysApp = baseMapper.selectById(sysAppReqVO.getId());
        Optional.ofNullable(sysApp).orElseThrow(() -> BizException.build("未找到要修改的应用信息"));
        checkRepeat(sysAppReqVO);
        //这两个字段不能修改,直接设置为null
        sysAppReqVO.setClientType(null);
        sysAppReqVO.setType(null);

        // 新增和编辑逻辑相同的情况下 直接调用新增或编辑方法
        return this.addOrUpdate(sysAppReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysAppRespVO addOrUpdate(SysAppReqVO sysAppReqVO) {
        SysApp sysApp2Save = sysAppReqVO.convertToEntity();
        boolean success = this.saveOrUpdate(sysApp2Save);
        if (success) {
            return SysAppRespVO.convertFromEntity(sysApp2Save);
        } else {
            BizException.throwException("操作失败，请刷新后重试");
        }
        return null;
    }

    private void checkRepeat(SysAppReqVO sysAppReqVO) {
        SysApp oldSysApp = lambdaQuery().eq(SysApp::getClientType,sysAppReqVO.getClientType())
                .eq(SysApp::getName, sysAppReqVO.getName()).eq(SysApp::getAppVersion, sysAppReqVO.getAppVersion()).one();
        if (sysAppReqVO.getId() == null && oldSysApp != null) {
            BizException.throwException("应用名称和版本号已存在");
        }
        if (sysAppReqVO.getId() != null && oldSysApp != null) {
            if (!oldSysApp.getId().equals(sysAppReqVO.getId())) {
                BizException.throwException("应用名称和版本号已存在");
            }
        }
    }

    @Override
    public SysAppRespVO getDetailById(Long sysAppId) {
        SysApp sysApp = baseMapper.selectById(sysAppId);
        Optional.ofNullable(sysApp).orElseThrow(() -> BizException.build("未找到对应应用信息"));
        return SysAppRespVO.convertFromEntity(sysApp);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(Long[] sysAppIds) {
        if (sysAppIds.length > 0) {
            this.removeByIds(Arrays.asList(sysAppIds));
        }
    }

    @Override
    public void enableSwitch(Long sysAppId) {
        SysApp sysApp = getById(sysAppId);
        lambdaUpdate().set(SysApp::getEnable, !sysApp.getEnable()).eq(SysApp::getId, sysAppId).update();
    }
}
